#include<sys/types.h>
#include <netinet/tcp.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<iostream>
#include<string>
#include<cstring>
#include <unistd.h>
#include <cassert>
using namespace std;

#define BUFFER_SIZE 64


int main(int argc,char** argv)
{
		const char* OpenNagle=argv[1];

		char read_buf[BUFFER_SIZE];
		char write_buf[BUFFER_SIZE];
		
		int ret=0;
		int port=9527;
		const char* ip="127.0.0.1";

		struct sockaddr_in address;
		bzero(&address,sizeof(address));
		address.sin_family=AF_INET;
		inet_pton(AF_INET,ip,&address.sin_addr);
		address.sin_port=htons(port);

		int listenfd=socket(PF_INET,SOCK_STREAM,0);
		assert(listenfd>=0);

		ret=bind(listenfd,(struct sockaddr*)&address,sizeof(address));
		assert(ret!=-1);

		ret=listen(listenfd,1);

		while(1)
		{
				struct sockaddr_in client;
				socklen_t client_addrlength=sizeof(client);
				int connfd=accept(listenfd,(struct sockaddr*)&client,&client_addrlength);
				if(OpenNagle=="close")//设置nagle算法
				{
						int on=1;
						setsockopt(connfd, SOL_SOCKET, TCP_NODELAY, (void *)&on, sizeof(on));
				}
				auto len=recv(connfd,&read_buf,BUFFER_SIZE-1,0);
				printf("%s",read_buf);
				cout<<endl;
				int num1=0;
				int num2=0;
				int i=0;
				for(i;i<len;i++)
				{
					if(read_buf[i]>='0'&&read_buf[i]<='9')
					{
						num1=num1*10+(int)(read_buf[i]-'0');
					}
					else
					{
						break;
					}
				}
				cout<<num1<<endl;
				
				if(i==BUFFER_SIZE||read_buf[i]!='+'||(read_buf[i]=='+'&&i==0))
				{
					read_buf[0]='0';
					send(connfd,read_buf,1,0);
					break;
				}
				i++;
				for(i;i<len;i++)
				{
					num2=num2*10+(int)(read_buf[i]-'0');
					cout<<num2<<endl;
				}
				cout<<num2;
				int sum=num1+num2;
				cout<<sum;
				string cnt=to_string(sum);
				strcpy(write_buf,cnt.c_str());
				send(connfd,write_buf,cnt.size(),0);
				break;
		}
		close(listenfd);
		return 0;
}
